<style>
  .ivu-tag:not(.ivu-tag-border):not(.ivu-tag-dot):not(.ivu-tag-checked) {
    background: #ddb077;
    border: 0;
    color: #fff;
}
</style>
<template>
  <div class="article-write_page">
      <Form :model="articleForm" :label-width="80" :rules="ruleInline" ref="articleForm">
          <FormItem label="文章标题" prop='contentTitle'>
              <Input v-model="articleForm.contentTitle" placeholder="Enter something..."></Input>
          </FormItem>
          <FormItem label="分类专栏" prop='lanmu' style="width:200px;display:inline-block;margin-right:60px;">
              <Select v-model="articleForm.lanmu">
                  <Option value="0">技术杂谈</Option>
                  <Option value="1">生活随笔</Option>
              </Select>
          </FormItem>
           <FormItem label="文章类别" prop='classify' style="width:200px;display:inline-block">
              <Select v-model="articleForm.classify">
                  <Option value="0">原创</Option>
                  <Option value="1">转载</Option>
                  <Option value="2">翻译</Option>
              </Select>
          </FormItem>
          <FormItem label="发布日期" style="width:400px">
              <Row>
                  <Col span="11">
                      <DatePicker type="date" placeholder="Select date" v-model="articleForm.date" @on-change="date"></DatePicker>
                  </Col>
                  <Col span="2" style="text-align: center">-</Col>
                  <Col span="11">
                      <TimePicker type="time" placeholder="Select time" v-model="articleForm.time"></TimePicker>
                  </Col>
              </Row>
          </FormItem>
          <FormItem label="文章标签" prop='tag'>
            <Tag  :checkable="true"  v-for="item in existTag" :key="item" :name="item" @on-change='checkedTag'>{{ item }}</Tag>
            <Tag  :checkable="true" v-for="item in addTag" :key="item"  :name="item" closable @on-change='checkedTag' @on-close="handleClose2">{{ item }}</Tag>
            <Button icon="ios-add" type="dashed" size="small" @click="handleAdd">添加标签</Button>
          </FormItem>
          <FormItem :label-width="0" prop='content'> 
               <div class="edit_container">
                    <quill-editor 
                    v-model="articleForm.content"
                    ref="myQuillEditor"
                    style="height:300px;"
                    :options="editorOption"
                    @change="onEditorChange($event)">
                    </quill-editor>
                </div> 
                <Progress :percent="percent" :stroke-width="20" status="active" text-inside  v-if="isShow"/>
                 <Upload
                    ref="uploadpic"
                    :format="['jpg','jpeg','png','gif']"
                    :max-size="2048"
					accept="image/*"
                    :before-upload="handleBeforeUpload1"
                    action="//jsonplaceholder.typicode.com/posts/">
                     <Button style="display:none" id="picFile"></Button>
                </Upload>
				<Upload
                    ref="uploadVideo"
                    :max-size="512000"
					accept="video/*"
                    :before-upload="beforeUploadVideo"
                    action="//jsonplaceholder.typicode.com/posts/">
                     <Button style="display:none" id="videoFile"></Button>
                </Upload>
          </FormItem>
          <FormItem>
              <Button type="primary" @click="submitArticle('articleForm')">Submit</Button>
              <Button style="margin-left: 8px">Cancel</Button>
          </FormItem>
      </Form>
       <Modal
        v-model="modal"
        title="添加标签"
        @on-ok="addTagOk()">
        <div>
            <input type="text" v-model="addTagName" maxlength="5" autofocus placeholder="限长5个字符">
        </div>
    </Modal>
		<Modal
        v-model="m1"
        title="本地or外链"
        @on-ok="waiLink()">
        <div>
			本地：<button @click="local">本地插入</button>
            外链：<input type="text" v-model="wai_link" autofocus >
        </div>
    </Modal>
    </div>
</template>
<script>
/* eslint-disable */
import Quill from 'quill'
import {mapMutations} from 'vuex'
import * as qiniu from 'qiniu-js'
    export default {
        data () {
            return {
                percent:0,
                isShow:false,
				wai_link:'',
				img_or_video:false,
				m1:false,
                modal:false,
                ischecked:[],
                addTagName:'',
                articleForm: {
                    contentTitle: '',
                    lanmu: '',
                    classify: '',
                    date: '',
                    time: '',
                    content: ``,
                    desc:``,
                    tag:[],
                },
                ruleInline: {
                   contentTitle: [
                        { required: true, message: 'Please fill in the title', trigger: 'blur',max:30 }
                    ],
                    lanmu: [
                        { required: true, message: 'Please fill in the value', trigger: 'blur'}
                    ],
                    classify: [
                        { required: true, message: 'Please fill in the value.', trigger: 'blur' }
                    ],
                    content: [
                        { required: true, message: 'Please fill in the content.', trigger: 'blur' }
                    ],
                },
                addTag: [],
                existTag:[],
                imgName: '',
                visible: false,
				pic:'',
				video:'',
				imgUS:[],
				videoUS:[],
                editorOption: {
                },
            }//return
        },
        computed: {
            editor() {
                return this.$refs.myQuillEditor.quill;
            },
        },
        methods:{
            ...mapMutations(['changeCanPost']),
            date(v1){
                this.articleForm.date = v1                
            },
            addTagOk(){
                let arr3 = this.existTag.concat(this.addTag)
                let sf = true;
                arr3.forEach(item => {
                    if(item.toUpperCase() == this.addTagName.toUpperCase()){
                        this.$Message.error('已经有该标签了！')
                        sf = false;
                        return;
                    }
                });
                if(sf){
                    this.addTag.push(this.addTagName)
                }                
                 this.addTagName = '';
            },
            checkedTag(checked,name){
                if(!checked){
                     if(this.articleForm.tag.length >= 1){
                        this.$Message.error('一篇文章只能有1个标签,多选只会选择前面1个')
                        return;
                    }
                    this. articleForm.tag.push(name)
                }else{
                    //取消选择标签
                    this. articleForm.tag =this. articleForm.tag.filter(function(item) {
                        return item != name
                    });
                }
                
                
            },
            //标签
           handleAdd () {
               this.modal = true;
            },
            handleClose2 (event, name) {
                const index = this.addTag.indexOf(name);
                this.addTag.splice(index, 1);
            },
            init(){
                this.$axios.get('/api/manage/tag/get').then(res =>{
                    if(res.data.err_code == 1){
                        this.existTag = res.data.data
                    }
                })
            },
            uploadImg: async function() {
                var vm = this
                vm.imageLoading = true
                var formData = {}
                try {
                const url = await vm.uploadImgReq(formData)// 自定义的图片上传函数
                if (url != null && url.length > 0) {
                    var value = url
                    vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection()
                    value = value.indexOf('http') != -1 ? value : 'http:' + value
                    vm.$refs.myQuillEditor.quill.insertEmbed(vm.addImgRange != null?vm.addImgRange.index:0, 'image', value, Quill.sources.USER)
                } else {
                    vm.$message.warning("图片增加失败")
                }
                document.getElementById(vm.uniqueId).value=''
                } catch ({message: msg}) {
                document.getElementById(vm.uniqueId).value=''
                vm.$message.warning(msg)
                }
                vm.imageLoading = false
          },
		  //外链插入image  or video
		  waiLink(){
			  this.m1 = false
			  if(!this.wai_link){
				  return false;
			  }
			  let quill = this.$refs.myQuillEditor.quill
			  quill.focus()
				// 获取光标所在位置
			let length = quill.getSelection().index;
			  if(this.img_or_video){
				  //video
				  quill.insertEmbed(length, 'video', this.wai_link)
				// 调整光标到最后
				quill.setSelection(length + 1)
			  }else{
				  //image
				// 插入图片 res.info为服务器返回的图片地址
				quill.insertEmbed(length, 'image', this.wai_link)
				// 调整光标到最后
				quill.setSelection(length + 1)
			  }
			  this.wai_link = '';
		  },
		  // 本地插入，上传
		  local(){
              this.m1 = false
               let now = (new Date().getTime())/1000 - parseInt(this.$store.state.canpost) /1000
                if(now < 1800){
                    this.$Message.error('间隔30分钟一篇文章')
                    return false;
                }
			  //视频
			  if(this.img_or_video){
				  let videoBtn = document.getElementById('videoFile') //隐藏的file文本ID
                videoBtn.click() //加一个触发事件
			  }else{
				  //image
				let fileInput = document.getElementById('picFile') //隐藏的file文本ID
                fileInput.click() //加一个触发事件
			  }
		  },
            handleBeforeUpload1 (file) {
                if(file){
                    if((file.size / 1024) > 2048){
                        this.$Notice.error({
                            title: '图片超过2M'
												});
												return false;
                     }else{
											this.pic = file
											this.getUploadToken()
										 }
                }
                return false;
			},
			beforeUploadVideo(file) {
                if(file){
                    if(((file.size / 1024)/1024) > 500){
                        this.$Notice.error({
                            title: '视频超过500M'
						});
						return false;
                     }else{
						this.video = file
						this.uploadVideo()
					}
                }
                return false;
            }, 
            //video upload
            async uploadVideo(){
               let res = await this.$axios.get('/api/uploadToken')
               if(res.data.code == 0){
                    this.$router.push('/')
               }else if(res.data.code == 1){
					let file = this.video
					let putExtra = {
							fname: file,
							params: {}, 
							mimeType: []
					};
					let config = {
							useCdnDomain: true, 
					};
					let that = this
					let observe = {
						next (res) {
                            that.isShow = true
                            that.percent = parseInt(res.total.percent)
                        },
						error (err) {
                            if(err){
                                that.$Notice.error({
                                    title: '视频上传失败'
                                })
                              
                            }
						},
                        complete (res) {
                            that.isShow = false;
                            if(res){
                                let picUrl = `http://q5knt7671.bkt.clouddn.com/${res.key}`
                                let quill = that.$refs.myQuillEditor.quill
                                    quill.focus()
                                // 获取光标所在位置
                                let length = quill.getSelection().index;
                                that.videoUS.push(res.key)
                                // 插入图片 res.info为服务器返回的图片地址
                                quill.insertEmbed(length, 'video', picUrl)
                                // 调整光标到最后
                                quill.setSelection(length + 1)
                            }
                        }
                    };
                    let key = new Date().getTime()
                    let observable = qiniu.upload(file,key, res.data.token, putExtra, config)
					let subscription = observable.subscribe(observe) // 这样传参形式也可以
               }
            },
            //  image upload
           async getUploadToken(){
               let res = await this.$axios.get('/api/uploadToken')
               if(res.data.code == 0){
                    this.$router.push('/')
               }else if(res.data.code == 1){
					let file = this.pic
					let putExtra = {
							fname: file,
							params: {}, 
							mimeType: ["image/png", "image/jpeg", "image/gif","image/jpeg"]
					};
					let config = {
							useCdnDomain: true, 
					};
					let that = this
					let observe = {
                        next (res) { 
                            console.log(res.total.percent);},
						error (err) {
                            if(err){
                                that.$Notice.error({
                                    title: '图片上传失败'
                                })
                              
                            }
						},
                        complete (res) {
                            if(res){
                                let picUrl = `http://q5knt7671.bkt.clouddn.com/${res.key}`
                                let quill = that.$refs.myQuillEditor.quill
                                    quill.focus()
                                // 获取光标所在位置
                                let length = quill.getSelection().index;
                                that.imgUS.push(res.key)
                                // 插入图片 res.info为服务器返回的图片地址
                                quill.insertEmbed(length, 'image', picUrl)
                                // 调整光标到最后
                                quill.setSelection(length + 1)
                            }
                        }
                    };
                    let key = new Date().getTime()
                    let observable = qiniu.upload(file,key, res.data.token, putExtra, config)
					let subscription = observable.subscribe(observe) // 这样传参形式也可以
               }
            },
            
            //文章内容提交
            submitArticle(name){
                 this.$refs[name].validate((valid) => {
                    if (valid) {
                        let now = (new Date().getTime())/1000 - parseInt(this.$store.state.canpost) /1000
                        if(now < 1800){
                            this.$Message.error('间隔30分钟一篇文章')
                            return false;
                        }
                         const that = this
                         let strLength =  parseInt(Math.random() * 40 + 60)
						that.articleForm.desc = that.articleForm.desc.slice(0,strLength)
						//获取文章第一张图片作为封面
                        this.articleForm.cover = this.getArticleImage(this.articleForm.content)
                        this.articleForm.imgUS = this.imgUS
                        this.articleForm.videoUS = this.videoUS
                        this.imgUS = []
                        this.videoUS = []
                         this.$axios.post('/api/manage/article/save',this.articleForm).then(res =>{
                            if(res.data.err_code == 0){
                              that.$router.push('/login')
                            }else if(res.data.err_code == 1){
                              that.$Message.error('没查询到用户！')
                            }else if(res.data.err_code == 3){
                              that.$refs.articleForm.resetFields();
                              that.$Message.success('文章发布成功！')
                              that.changeCanPost({canpost:new Date().getTime()})
                            }else if(res.data.err_code == 4){
                              that.$Message.error('参数有误！')
                            }else{
                              that.$Message.error('服务器出错！')
                            }
                          })
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            onEditorChange(data){
                this.articleForm.desc = data.text
						},
						getArticleImage(str){
							 var data = '';
            		str.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/, function (match, capture) {
                  data =  capture;
           		 });
       					 return data
						}
        },
        mounted(){
            this.init()
            var vm =this
            var imgHandler = async function(image) {
				vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection()
				if (image) {
					vm.img_or_video = false
					vm.m1 = true;
				}
            }
			vm.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("image", imgHandler)
			var imgHandler = async function(video) {
				vm.addImgRange = vm.$refs.myQuillEditor.quill.getSelection()
				if (video) {
					vm.img_or_video = true
					vm.m1 = true;
				}
            }
            vm.$refs.myQuillEditor.quill.getModule("toolbar").addHandler("video", imgHandler)
        }
	}
</script>
